/**
 * 玩家实体类
 * 表示AI侦探应用中的玩家用户
 */
export enum PlayerRole {
  DETECTIVE = 'detective',    // 侦探
  ASSISTANT = 'assistant',    // 助手
  ADMIN = 'admin',           // 管理员
  GUEST = 'guest'           // 访客
}

export enum PlayerStatus {
  ACTIVE = 'active',        // 活跃
  INACTIVE = 'inactive',    // 非活跃
  BANNED = 'banned',        // 被封禁
  PREMIUM = 'premium'       // 高级用户
}

export enum PlayerLevel {
  NOVICE = 'novice',        // 新手
  AMATEUR = 'amateur',      // 业余
  PROFESSIONAL = 'professional', // 专业
  EXPERT = 'expert',        // 专家
  MASTER = 'master'         // 大师
}

export interface PlayerStats {
  totalCases: number;        // 总案件数
  solvedCases: number;       // 解决案件数
  failedCases: number;       // 失败案件数
  currentStreak: number;     // 当前连胜
  maxStreak: number;         // 最大连胜
  totalScore: number;        // 总分数
  averageScore: number;      // 平均分
  totalTimeSpent: number;    // 总时间(秒)
  averageTimePerCase: number; // 平均每个案件时间
  accuracy: number;          // 准确率
  rank: number;             // 排名
}

export interface PlayerPreferences {
  theme: 'light' | 'dark' | 'auto';     // 主题
  language: string;                        // 语言
  notifications: boolean;                  // 通知
  soundEffects: boolean;                   // 音效
  autoSave: boolean;                       // 自动保存
  difficulty: 'easy' | 'medium' | 'hard'; // 默认难度
  caseCategory: string[];                  // 喜欢的案件类型
}

export interface Player {
  id: string;
  username: string;
  email: string;
  nickname: string;
  avatar?: string;
  role: PlayerRole;
  status: PlayerStatus;
  level: PlayerLevel;
  experience: number;        // 经验值
  levelProgress: number;     // 等级进度(0-100)
  coins: number;              // 金币
  gems: number;               // 宝石
  stats: PlayerStats;
  preferences: PlayerPreferences;
  createdAt: string;
  lastLoginAt: string;
  lastActiveAt: string;
  totalPlayTime: number;      // 总游戏时间(秒)
  dailyPlayTime: number;      // 今日游戏时间(秒)
  weeklyPlayTime: number;     // 本周游戏时间(秒)
  friendList: string[];       // 好友列表
  achievementList: string[];  // 成就列表
  currentCaseId?: string;     // 当前进行中的案件ID
  completedCaseIds: string[];  // 完成的案件ID列表
  favoriteCaseIds: string[];  // 收藏的案件ID列表
  isOnline: boolean;
  sessionId?: string;         // 会话ID
  deviceInfo?: {              // 设备信息
    platform: string;
    deviceModel: string;
    osVersion: string;
  };
  location?: {                // 位置信息
    country: string;
    city: string;
    timezone: string;
  };
  subscription?: {          // 订阅信息
    type: 'free' | 'premium' | 'vip';
    startDate: string;
    endDate: string;
    autoRenew: boolean;
  };
}

/**
 * 创建新玩家的工厂函数
 */
export function createPlayer(data: Partial<Player> = {}): Player {
  const now = new Date().toISOString();
  const defaultStats: PlayerStats = {
    totalCases: 0,
    solvedCases: 0,
    failedCases: 0,
    currentStreak: 0,
    maxStreak: 0,
    totalScore: 0,
    averageScore: 0,
    totalTimeSpent: 0,
    averageTimePerCase: 0,
    accuracy: 0,
    rank: 0
  };
  
  const defaultPreferences: PlayerPreferences = {
    theme: 'auto',
    language: 'zh-CN',
    notifications: true,
    soundEffects: true,
    autoSave: true,
    difficulty: 'medium',
    caseCategory: []
  };
  
  return {
    id: data.id || generatePlayerId(),
    username: data.username || `player_${Date.now().toString(36)}`,
    email: data.email || '',
    nickname: data.nickname || '新玩家',
    avatar: data.avatar,
    role: data.role || PlayerRole.DETECTIVE,
    status: data.status || PlayerStatus.ACTIVE,
    level: data.level || PlayerLevel.NOVICE,
    experience: data.experience || 0,
    levelProgress: data.levelProgress || 0,
    coins: data.coins || 100,
    gems: data.gems || 0,
    stats: data.stats || defaultStats,
    preferences: data.preferences || defaultPreferences,
    createdAt: data.createdAt || now,
    lastLoginAt: data.lastLoginAt || now,
    lastActiveAt: data.lastActiveAt || now,
    totalPlayTime: data.totalPlayTime || 0,
    dailyPlayTime: data.dailyPlayTime || 0,
    weeklyPlayTime: data.weeklyPlayTime || 0,
    friendList: data.friendList || [],
    achievementList: data.achievementList || [],
    currentCaseId: data.currentCaseId,
    completedCaseIds: data.completedCaseIds || [],
    favoriteCaseIds: data.favoriteCaseIds || [],
    isOnline: data.isOnline !== undefined ? data.isOnline : true,
    sessionId: data.sessionId,
    deviceInfo: data.deviceInfo,
    location: data.location,
    subscription: data.subscription || {
      type: 'free',
      startDate: now,
      endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
      autoRenew: false
    },
    ...data
  };
}

/**
 * 生成玩家ID
 */
function generatePlayerId(): string {
  const timestamp = Date.now();
  const random = Math.random().toString(36).substr(2, 9);
  return `PLAYER-${timestamp}-${random}`;
}

/**
 * 获取玩家角色的中文名称
 */
export function getPlayerRoleName(role: PlayerRole): string {
  const roleNames = {
    [PlayerRole.DETECTIVE]: '侦探',
    [PlayerRole.ASSISTANT]: '助手',
    [PlayerRole.ADMIN]: '管理员',
    [PlayerRole.GUEST]: '访客'
  };
  return roleNames[role];
}

/**
 * 获取玩家状态的中文名称
 */
export function getPlayerStatusName(status: PlayerStatus): string {
  const statusNames = {
    [PlayerStatus.ACTIVE]: '活跃',
    [PlayerStatus.INACTIVE]: '非活跃',
    [PlayerStatus.BANNED]: '被封禁',
    [PlayerStatus.PREMIUM]: '高级用户'
  };
  return statusNames[status];
}

/**
 * 获取玩家等级的中文名称
 */
export function getPlayerLevelName(level: PlayerLevel): string {
  const levelNames = {
    [PlayerLevel.NOVICE]: '新手',
    [PlayerLevel.AMATEUR]: '业余',
    [PlayerLevel.PROFESSIONAL]: '专业',
    [PlayerLevel.EXPERT]: '专家',
    [PlayerLevel.MASTER]: '大师'
  };
  return levelNames[level];
}

/**
 * 计算等级进度
 */
export function calculateLevelProgress(experience: number, level: PlayerLevel): number {
  const levelThresholds = {
    [PlayerLevel.NOVICE]: 0,
    [PlayerLevel.AMATEUR]: 100,
    [PlayerLevel.PROFESSIONAL]: 500,
    [PlayerLevel.EXPERT]: 1500,
    [PlayerLevel.MASTER]: 3000
  };
  
  const currentThreshold = levelThresholds[level];
  const nextThreshold = levelThresholds[getNextLevel(level)] || currentThreshold * 2;
  
  if (experience >= nextThreshold) return 100;
  if (experience <= currentThreshold) return 0;
  
  return Math.round(((experience - currentThreshold) / (nextThreshold - currentThreshold)) * 100);
}

/**
 * 获取下一等级
 */
export function getNextLevel(currentLevel: PlayerLevel): PlayerLevel | null {
  const levels = [PlayerLevel.NOVICE, PlayerLevel.AMATEUR, PlayerLevel.PROFESSIONAL, PlayerLevel.EXPERT, PlayerLevel.MASTER];
  const currentIndex = levels.indexOf(currentLevel);
  return currentIndex < levels.length - 1 ? levels[currentIndex + 1] : null;
}

/**
 * 计算玩家准确率
 */
export function calculateAccuracy(stats: PlayerStats): number {
  const total = stats.solvedCases + stats.failedCases;
  return total > 0 ? Math.round((stats.solvedCases / total) * 100) : 0;
}

/**
 * 计算平均分
 */
export function calculateAverageScore(stats: PlayerStats): number {
  return stats.totalCases > 0 ? Math.round(stats.totalScore / stats.totalCases) : 0;
}

/**
 * 计算平均每个案件时间
 */
export function calculateAverageTimePerCase(stats: PlayerStats): number {
  return stats.totalCases > 0 ? Math.round(stats.totalTimeSpent / stats.totalCases) : 0;
}